/**
 * @(#) ForeignAdjustMediator.as
 *
 * @date		2009. 04. 03.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	국외출장 실비입력 - Mediator
 */
package com.skt.common_hr.biztrip_nos.view
{
	import com.skt.common_hr.biztrip_nos.BizTripFacade;
	import com.skt.common_hr.biztrip_nos.events.ImportCardEvent;
	import com.skt.common_hr.biztrip_nos.model.BizTripCodesProxy;
	import com.skt.common_hr.biztrip_nos.model.CompanyCreditCardProxy;
	import com.skt.common_hr.biztrip_nos.model.DailyCostProxy;
	import com.skt.common_hr.biztrip_nos.model.vo.AdjustDataPackage;
	import com.skt.common_hr.biztrip_nos.model.vo.BizTripCodesVO;
	import com.skt.common_hr.biztrip_nos.model.vo.CompanyCreditCardVO;
	import com.skt.common_hr.biztrip_nos.model.vo.DailyCostVO;
	import com.skt.common_hr.biztrip_nos.model.vo.MemberCarfareVO;
	import com.skt.common_hr.biztrip_nos.model.vo.MemberDetailCostVO;
	import com.skt.common_hr.biztrip_nos.view.components.ForeignAdjustViewNos;
	import com.skt.common_hr.biztrip_nos.view.components.ImportCompanyCardsNos;
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.wcl.utils.DateUtil;
	
	import flash.display.Sprite;
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.core.IFlexDisplayObject;
	import mx.managers.PopUpManager;
	import mx.resources.ResourceManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;

	public class ForeignAdjustMediator extends CommonMediator
	{
		public static const NAME:String = "ForeignAdjustMediator"; 

		[Bindable] static public var costTypeList:ArrayCollection;
		[Bindable] static public var evidenceTypeList:ArrayCollection; 
		[Bindable] static public var currencyList:ArrayCollection;
		
		private var key1:String;
		private var key2:String;
		private var TRSTATUS:String = "21";
		private var bModify:Boolean = true;
		private var adjustDataPackage:AdjustDataPackage;
		
		private var gasCost:Number = 0;
		
		private var importCardView:IFlexDisplayObject;

		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function ForeignAdjustMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
            view.callLater(initView);
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		private function initView():void
 		{
			//loadBizTripList();
			//set event handlers...
			view.addEventListener(ForeignAdjustViewNos.IMPORT_CARD_LIST, onImportCardList);
			view.addEventListener(ForeignAdjustViewNos.CONFIRM, onClickConfirm);
			view.addEventListener(ForeignAdjustViewNos.CANCEL, onClickCancel);
			view.addEventListener(ForeignAdjustViewNos.CHANGED_DAILY_COST, onChangedDailyCost);
			view.addEventListener(ForeignAdjustViewNos.CHANGED_VEHICLE, onChangedVehicle);
 			initViewData();
 		}
 		
 		private function initViewData():void
 		{
 			var codeProxy:BizTripCodesProxy = facade.retrieveProxy(BizTripCodesProxy.NAME) as BizTripCodesProxy;
 			//view.evidenceList = codeProxy.evidenceTypes;
 			evidenceTypeList = new ArrayCollection();
 			for each(var vo1:BizTripCodesVO in codeProxy.evidenceTypes) {
 				if(vo1.CODE != "01") {		// 법인카드 제외
 					evidenceTypeList.addItem(vo1);	
 				}
 			}
 			costTypeList = new ArrayCollection();
			var cost:BizTripCodesVO = new BizTripCodesVO();
			cost.TYPE		= "01";
			cost.CODE		= "00";
			cost.TEXT		= ResourceManager.getInstance().getString(commonFacade.bundle, "COST_TYPE02", null, Variables.current_locale);
			costTypeList.addItem(cost);
 			for each(var vo2:BizTripCodesVO in codeProxy.costTypes) {
 				if(vo2.TYPE == BizTripFacade.TYPE_FOREIGN_BIZTRIP) {	// 국내출장에 해당하는 비용구분만 뽑아냄
 					costTypeList.addItem(vo2);
 				}
 			}
 			
 			currencyList = codeProxy.currencyTypes;
 		}
 		
 		override protected function clearView():void
 		{
 			//initViewData();
 		}
 		
 		private function modeReadOnly():void
 		{
 			trace("modeReadOnly");
 			bModify = false;
 			view.currentState = "readonly";
 		}
 		
 		private function modeModify():void
 		{
 			trace("modeModify");
 			bModify = true;
 			view.currentState = "";
 		}
 		
		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return [
					BizTripFacade.READONLY_DOMESTIC_VIEW,
					BizTripFacade.MODIFY_DOMESTIC_VIEW,
					BizTripFacade.PERSONAL_FOREIGN_ADJUSTMENT,
					BizTripFacade.PERSONAL_FOREIGN_ADJUSTMENT_READONLY,
					BizTripFacade.LOAD_USEDCARDLIST_COMPLETE,
					BizTripFacade.LOAD_DAILY_COST_COMPLETE,
					BizTripFacade.LOAD_DAILY_COST_FAILED,
					BizTripFacade.LOAD_DAILY_COST_FOREIGN_COMPLETE,
					BizTripFacade.LOAD_DAILY_COST_FOREIGN_FAILED
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName()) 
			{
				case BizTripFacade.PERSONAL_FOREIGN_ADJUSTMENT:
					changeViewEditable();
					setData(note.getBody() as AdjustDataPackage);
					loadDailyCost(view.member.PERNR);
					break;
				case BizTripFacade.PERSONAL_FOREIGN_ADJUSTMENT_READONLY:
					changeViewReadOnly();
					setData(note.getBody() as AdjustDataPackage);
					//loadDailyCost(view.member.PERNR);
					break;
				case BizTripFacade.LOAD_USEDCARDLIST_COMPLETE:
					if(importCardView!=null) {
						if(note.getBody().usedCardList.length>0) {
							setImportCardList(note.getBody() as CompanyCreditCardProxy);
						}
						else {
							CommonAlert.showMessage(commonFacade.bundle, "ALERT_NO_USED_CARD", null, "TITLE_DEFAULT", importCardView as Sprite);
						}
					}
					break;
				case BizTripFacade.LOAD_USEDCARDLIST_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "("+dailyCostProxy.errCode+") "+ dailyCostProxy.errText);
					break;
				case BizTripFacade.LOAD_DAILY_COST_FOREIGN_COMPLETE:
					onLoadDailyCostForeign(note.getBody() as DailyCostProxy);
					break;
				case BizTripFacade.LOAD_DAILY_COST_FOREIGN_FAILED:
					trace("일비를 가져오는데 실패했습니다.");
					var dailyCostProxy:DailyCostProxy = note.getBody() as DailyCostProxy;
					CommonAlert.showMessage(commonFacade.bundle, "("+dailyCostProxy.errCode+") "+ dailyCostProxy.errText);
					break;
				case BizTripFacade.LOAD_DAILY_COST_COMPLETE:
					onLoadDailyCost(note.getBody() as DailyCostProxy);
					break;
				case BizTripFacade.LOAD_DAILY_COST_FAILED:
					{
						trace("일비를 가져오는데 실패했습니다."); 
						var dailyCostProxy1:DailyCostProxy = note.getBody() as DailyCostProxy;
						CommonAlert.showMessage(commonFacade.bundle, "("+dailyCostProxy1.errCode+") "+ dailyCostProxy1.errText);
					}
					break;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}
		
		
		
		private function setData(dataPackage:AdjustDataPackage):void
		{
			adjustDataPackage = dataPackage;
			
			view.member = dataPackage.memberInfo;
			view.detailCost = dataPackage.memberDetailCost;
			view.dailyCostList.removeAll();
			
			var carfare:ArrayCollection = new ArrayCollection();
			carfare.addItem(dataPackage.memberCarefare);
			view.carfare = carfare;

			// 일비 관련 처리 
			// 일비 지급 이면
			if(dataPackage.memberCarefare.TRTICH == "X") {
				setOrgDailyCost();				
			}
		}
		
		private function setOrgDailyCost():void
		{
			var dailyCost:DailyCostVO = new DailyCostVO;
			dailyCost.PERNR = adjustDataPackage.memberInfo.PERNR;
			dailyCost.days 	= getTripDays();
			dailyCost.AMT 	= adjustDataPackage.memberAdjust.DAYPY;
			view.dailyCostList.addItem(dailyCost);
		}
		
		private function changeViewEditable():void
		{
			view.modeEditable = true;	
		}
		
		private function changeViewReadOnly():void
		{
			view.modeEditable = false;	
		}
		
		
 		private function loadDailyCost(pernr:String):void
 		{
 			var proxy:DailyCostProxy = facade.retrieveProxy(DailyCostProxy.NAME) as DailyCostProxy;
 			//proxy.load(pernr, getTripDays(), adjustDataPackage.LAND);
			proxy.loadForeign(pernr, view.member.BEGDA, buildDailyCostData(pernr));	
 		}
 
		private function buildDailyCostData(pernr:String):Array
		{
			var table:Array = new Array;
			
			var vo:Object = new Object;
			vo.PERNR = pernr;
			vo.LAND1 = adjustDataPackage.LAND;
			vo.TRDAYS = getTripDays().toString();
			table.push(vo);
			return table;	
		}
		
 		private function getTripDays():Number
 		{
 			return DateUtil.DateDiff(view.member.BEGDA, view.member.ENDDA);
 		}
 
 		private function onLoadDailyCost(proxy:DailyCostProxy):void
 		{
 			view.dailyCostList.removeAll();
 			view.maxDailyCost = proxy.costList.getItemAt(0).AMT;
 			view.dailyCostList.addItem(proxy.costList.getItemAt(0));
 		}
 
 		private function onLoadDailyCostForeign(proxy:DailyCostProxy):void
 		{
 			trace("onLoadDailyCost:");
 			if(bModify) {
	 			view.maxDailyCost = proxy.costList.getItemAt(0).AMT;
	 			if(view.dailyCostList.length==0 || view.dailyCostList.getItemAt(0).AMT<=0) {  
		 			view.dailyCostList.removeAll();
		 			proxy.costList.getItemAt(0).days = getTripDays();
		 			view.dailyCostList.addItem(proxy.costList.getItemAt(0));
		 		}
		 	}
 		}
 
 
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Event handler (from View, Internal or....)
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		
 		private function onImportCardList(event:Event):void
 		{
 			if(!importCardView) {
 				importCardView = PopUpManager.createPopUp(view.root, ImportCompanyCardsNos, true);
 				PopUpManager.centerPopUp(importCardView);
	 			importCardView.addEventListener(ImportCardEvent.LOAD_COMPANYCARD_LIST, loadImportCardList);
	 			importCardView.addEventListener(ImportCompanyCardsNos.OK_IMPORT_CARDLIST, onOkImport);
	 			importCardView.addEventListener(ImportCompanyCardsNos.CANCEL_IMPORT_CARDLIST, onCancelImport);
 			}
 			else {
 				PopUpManager.addPopUp(importCardView, view.root, true);
 				PopUpManager.centerPopUp(importCardView);
 			}
 			(importCardView as ImportCompanyCardsNos).setFocus();
 			(importCardView as ImportCompanyCardsNos).usedList = new ArrayCollection();
 			
 			//importCardView.x = 545;
 			//importCardView.y = 80;
 		}
 		
 
		private function loadImportCardList(event:ImportCardEvent):void
		{
			var proxy:CompanyCreditCardProxy = facade.retrieveProxy(CompanyCreditCardProxy.NAME) as CompanyCreditCardProxy;
			
			var begda:Date = adjustDataPackage.memberInfo.BEGDA;
			//begda.month = 0; begda.date = 1;
			var endda:Date = adjustDataPackage.memberInfo.ENDDA;
			//endda.month = 11; endda.date = 31;
			
			proxy.load(event.CardNo, begda, endda);
		}

		private function setImportCardList(proxy:CompanyCreditCardProxy):void
		{
			for(var i:int=0; i<proxy.usedCardList.length; ) {
				if(findDetailCost(proxy.usedCardList.getItemAt(i).APNO)>=0) {
					proxy.usedCardList.removeItemAt(i);
				}
				else {
					i++;
				}
			}
			if(proxy.usedCardList.length<1) {
				CommonAlert.showMessage(commonFacade.bundle, "ALERT_NO_USED_CARD02", null, "TITLE_DEFAULT", importCardView as Sprite);
			}
			(importCardView as ImportCompanyCardsNos).usedList= proxy.usedCardList;
		}
		
		private function findDetailCost(apno:String):int
		{
			for(var i:int=0; i<this.adjustDataPackage.memberDetailCost.length; i++) {
				if(adjustDataPackage.memberDetailCost.getItemAt(i).APNO == apno) return i;
			}
			return -1;
		}
		
		private function onOkImport(event:Event):void
		{
			PopUpManager.removePopUp(importCardView);
			if(!view.detailCost) {
				view.detailCost = new ArrayCollection();
			}
			for each(var src:CompanyCreditCardVO in (importCardView as ImportCompanyCardsNos).usedList)
			{
				if(src.selected) {
					var vo:MemberDetailCostVO = new MemberDetailCostVO();
					vo.PERNR = view.member.PERNR;
					vo.CARDNO 	= src.CARDNO;
					vo.APNO 	= src.APNO;
					vo.RECGBN 	= "01";
					vo.RECTXT 	= ResourceManager.getInstance().getString(commonFacade.bundle, "COMPANY_CARD", null, Variables.current_locale);
					vo.RDATE 	= new Date(src.APDAT);
					vo.AMT		= src.APAMT;
					vo.MERNM	= src.STNAME;
					vo.WAERS	= src.WAERS;
					vo.COSTGBN	= "00";
					view.detailCost.addItem(vo);
				}
			}
		}
		
		private function onCancelImport(event:Event):void
		{
			PopUpManager.removePopUp(importCardView);
		}
		
		private function onClickConfirm(event:Event):void
		{
			if(validate()) {
				adjustDataPackage.memberDetailCost = view.detailCost;
				setCarfare();
				facade.sendNotification(BizTripFacade.CONFIRM_FOREIGN_ADJUST_INPUT, adjustDataPackage);
				PopUpManager.removePopUp(view);
			}
		}

	
		public function onClickCancel(event:Event):void
		{
			facade.sendNotification(BizTripFacade.CANCEL_FOREIGN_ADJUST_INPUT, this);
			PopUpManager.removePopUp(view);
		}
		
		private function validate():Boolean
		{
			// 일비 한도체크
			
			if(view.maxDailyCost<view.dailyCostList.getItemAt(0).AMT) {
				CommonAlert.showMessage(commonFacade.bundle, "일비한도를 초과했습니다.", null, "TITLE_DEFAULT");
				return false;
			}
			
			for each(var cost:MemberDetailCostVO in view.detailCost)
			{
				if(cost.COSTGBN == "00") {
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_NO_INPUT_COST", null, "TITLE_DEFAULT");
					return false;
				}
				if(cost.RDATE == null) {
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_NO_INPUT_DATE", null, "TITLE_DEFAULT");
					return false;
				}
				if(cost.AMT == 0) {
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_NO_INPUT_AMT", null, "TITLE_DEFAULT");
					return false;
				}
			}
			return true;
		}
		
		public function onChangedDailyCost(event:Event):void
		{
			if(event.target.chkDailyCost.selected) {
				loadDailyCost(view.member.PERNR);
			}
		}
		
		public function onChangedVehicle(event:Event):void
		{
			
		}
		
		private function setCarfare():void
		{
			adjustDataPackage.memberCarefare = MemberCarfareVO(view.carfare.getItemAt(0).clone());
			//adjustDataPackage.memberCarefare.TRTICH = view.chkDailyCost.selected ? "X": "";
			if(view.chkDailyCost.selected) {
				adjustDataPackage.memberAdjust.TRTICH ="X";
				adjustDataPackage.memberAdjust.WAERS = "KRW";
				adjustDataPackage.memberAdjust.DAYPY = view.dailyCostList.getItemAt(0).AMT;
				adjustDataPackage.memberCarefare.TRTICH = "X"
				adjustDataPackage.memberCarefare.WAERS = "KRW";
				adjustDataPackage.memberCarefare.DAYPY = view.dailyCostList.getItemAt(0).AMT;
			}
			else {
				adjustDataPackage.memberAdjust.TRTICH ="";
				adjustDataPackage.memberAdjust.DAYPY = 0;
				adjustDataPackage.memberCarefare.TRTICH = ""
				adjustDataPackage.memberCarefare.DAYPY = 0;
			}
			/*
			if(view.chkPrivateVehicle.selected) {
				adjustDataPackage.memberCarefare.PCARC = "X";
				adjustDataPackage.memberCarefare.DRIKM = view.carfare.getItemAt(0).DRIKM;
				adjustDataPackage.memberCarefare.UNITAMT = view.carfare.getItemAt(0).UNITAMT;
				adjustDataPackage.memberAdjust.PCARC = "X";
				adjustDataPackage.memberAdjust.PCAPY = view.carfare.getItemAt(0).PDRPY;
			}
			else{
				adjustDataPackage.memberCarefare.PCARC = "";
				adjustDataPackage.memberAdjust.PCARC = "";
				adjustDataPackage.memberAdjust.PCAPY = 0;
			}
			*/
			
		}
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():ForeignAdjustViewNos
        {
            return viewComponent as ForeignAdjustViewNos;
        }
		
		
	}
}